package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.EmployeeMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.EmployeeService;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    //统计时间区间内的营业额
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        //日期计算
        for(int i = 0; !begin.plusDays(i).isAfter(end); i++){
            dateList.add((LocalDate) begin.plusDays(i));
        }
        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime= LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date, LocalTime.MAX);
            Double turnover= orderMapper.sumByMap(beginTime,endTime);
            turnover= turnover==null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    //统计指定时间区间内的用户数据
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        for(int i = 0; !begin.plusDays(i).isAfter(end); i++){
            dateList.add( begin.plusDays(i));
        }
        //每天新增用户数量
        List<Integer> newUserLiset=new ArrayList<>();
        //存放每天的总用户量
        List<Integer> totalUserLiset=new ArrayList<>();

        for(LocalDate date : dateList){
            LocalDateTime beginTime= LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put(end,endTime);
            Integer totalUser=userMapper.countByMap(map);
            totalUserLiset.add(totalUser);
            map.put(begin,beginTime);
            Integer newUser=userMapper.countByMap(map);
            newUserLiset.add(newUser);

        }







        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserLiset,","))
                .totalUserList(StringUtils.join(totalUserLiset,","))
                .build();
    }


    //统计指定时间区间内的订单数据
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        for(int i = 0; !begin.plusDays(i).isAfter(end); i++){
            dateList.add( begin.plusDays(i));
        }
        //查询每天订单总数
        List<Integer> orderCountList=new ArrayList<>();
        //查询每天有效订单数
        List<Integer> validOrderCountList=new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginTime= LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime= LocalDateTime.of(date, LocalTime.MAX);

            Integer orderCount= getOrderCount(beginTime,endTime,null);


            Integer validOrderCount= getOrderCount(beginTime,endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);

        }

        //计算时间区间内的订单总数
        Integer totalOrderCount= orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数
        Integer validOrderCount= validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率

        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0){
             orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount.doubleValue();
        }


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime= LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime= LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10=orderMapper.getSalesTop(beginTime,endTime);
        List<String> names= salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers=salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    //导出运营数据报表
    @Override
    public void exportBusinessData(HttpServletResponse response)  {
        //查询数据库获取营业数据
        LocalDate datebegin= LocalDate.now().minusDays(30);
        LocalDate dateend= LocalDate.now().plusDays(1);
        LocalDateTime begin=LocalDateTime.of(datebegin, LocalTime.MIN);
        LocalDateTime end=LocalDateTime.of(dateend, LocalTime.MAX);
        //查询概览数据
        BusinessDataVO vo = workspaceService.getBusinessData(begin,end);

        //通过POI将数据写入excel文件中
        try {
            //基于模板文件创建一个新的Excel文件
            InputStream in= new FileInputStream(new File("D:\\After\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));

            XSSFWorkbook excel=new XSSFWorkbook(in);
            //填充数据--时间
            XSSFSheet sheet= excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+datebegin+"至"+dateend);
            //获取第四行
            XSSFRow row= sheet.getRow(3);
            row.getCell(2).setCellValue(vo.getTurnover());
            row.getCell(4).setCellValue(vo.getOrderCompletionRate());
            row.getCell(6).setCellValue(vo.getNewUsers());

            //获取第五行
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(vo.getValidOrderCount());
            row.getCell(4).setCellValue(vo.getUnitPrice());

            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date=datebegin.plusDays(i);
                BusinessDataVO businessDataVo= workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                row=sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVo.getTurnover());
                row.getCell(3).setCellValue(businessDataVo.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVo.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVo.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVo.getNewUsers());

            }





            //通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out= response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();

        }
        catch (Exception e) {
            e.printStackTrace();
        }




    }

    //根据条件统计订单数量
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map map=new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }

}
